<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-title">电商后台管理系统</div>
      <div class="login-subtitle">欢迎使用，请登录</div>
      <el-alert
        class="login-alert"
        title="测试账号：+86 13800138000 / 密码：123456"
        type="info"
        show-icon
        :closable="false"
      />
      <el-form :model="form" :rules="rules" ref="formRef" label-width="0">
        <el-form-item prop="phone">
          <el-input
            v-model="form.phone"
            placeholder="请输入手机号"
            clearable
            prefix-icon="User"
          >
            <template #prepend>
              <el-select v-model="form.prefix" style="width: 120px">
                <el-option label="+86 中国" value="+86" />
                <el-option label="+852 香港" value="+852" />
                <el-option label="+853 澳门" value="+853" />
                <el-option label="+886 台湾" value="+886" />
                <el-option label="+81 日本" value="+81" />
                <el-option label="+1 美国" value="+1" />
                <el-option label="+44 英国" value="+44" />
                <el-option label="+49 德国" value="+49" />
                <el-option label="+33 法国" value="+33" />
                <el-option label="+61 澳大利亚" value="+61" />
                <el-option label="+82 韩国" value="+82" />
                <el-option label="+65 新加坡" value="+65" />
                <el-option label="+60 马来西亚" value="+60" />
                <el-option label="+66 泰国" value="+66" />
                <el-option label="+84 越南" value="+84" />
              </el-select>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="loginType === 'password'" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item v-if="loginType === 'code'" prop="code">
          <el-row gutter="8" style="width: 100%">
            <el-col :span="16">
              <el-input
                v-model="form.code"
                placeholder="请输入验证码"
                prefix-icon="Message"
                maxlength="6"
              />
            </el-col>
            <el-col :span="8">
              <el-button
                :disabled="countdown > 0 || !form.phone"
                @click="sendCode"
                style="width: 100%"
              >
                <span v-if="countdown === 0">获取验证码</span>
                <span v-else>{{ countdown }}秒</span>
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            style="width: 100%; height: 40px; border-radius: 4px"
            :loading="loading"
            @click="onLogin"
          >
            登录
          </el-button>
        </el-form-item>
        <el-form-item>
          <div class="login-switch">
            <el-link type="primary" @click="toggleType">
              {{ loginType === 'password' ? '使用验证码登录' : '使用密码登录' }}
            </el-link>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/store/auth'

const router = useRouter()
const auth = useAuthStore()
const formRef = ref()
const loginType = ref<'password' | 'code'>('password')
const loading = ref(false)
const countdown = ref(0)
let timer: any = null

const form = reactive({
  prefix: '+86',
  phone: '',
  password: '',
  code: ''
})

const fullPhone = computed(() => form.prefix + form.phone)

const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^\d{6,20}$/, message: '请输入有效手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码格式不正确', trigger: 'blur' }
  ]
}

function toggleType() {
  loginType.value = loginType.value === 'password' ? 'code' : 'password'
}

function sendCode() {
  if (!/^\d{6,20}$/.test(form.phone)) {
    ElMessage.error('请输入有效手机号')
    return
  }
  countdown.value = 60
  ElMessage.success('验证码已发送：123456（测试）')
  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
      timer = null
    }
  }, 1000)
}

async function onLogin() {
  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    loading.value = true
    setTimeout(() => {
      loading.value = false
      // 登录成功后，+8613800138000显示admin，其它显示手机号
      if (
        (loginType.value === 'password' && fullPhone.value === '+8613800138000' && form.password === '123456') ||
        (loginType.value === 'code' && fullPhone.value === '+8613800138000' && form.code === '123456')
      ) {
        const displayName = fullPhone.value === '+8613800138000' ? 'admin' : fullPhone.value
        auth.login({
          name: displayName,
          avatar: 'https://dummyimage.com/40x40/409eff/fff&text=U',
          token: 'mock-token'
        })
        ElMessage.success('登录成功')
        router.push('/')
      } else {
        ElMessage.error('账号或密码/验证码错误')
      }
    }, 1000)
  })
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.login-card {
  width: 420px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  padding: 40px 32px 24px 32px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.login-title {
  font-size: 28px;
  color: #303133;
  text-align: center;
  margin-bottom: 8px;
  font-weight: bold;
}
.login-subtitle {
  font-size: 14px;
  color: #909399;
  text-align: center;
  margin-bottom: 20px;
}
.login-alert {
  width: 100%;
  margin-bottom: 20px;
}
.login-switch {
  width: 100%;
  text-align: right;
}
@media (max-width: 768px) {
  .login-card {
    width: 90vw;
    padding: 24px 8px;
  }
  .el-select {
    width: 100px !important;
  }
}
</style>
